package com.demo.understandmvc.控制器增强.requestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;

import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import com.demo.understandmvc.返回值处理.responseEntity.MyData;

/**一个类不能同时两个接口，这会导致ResponseBodyAdvice无效，因为扫描时先判断Bean是否是RequestBodyAdvice接口的实现，如果是，则直接作为RequestBodyAdvice，而不会视为ResponseBodyAdvice
 * @author zhangsulei
 *
 */
@ControllerAdvice
public class MyRequestBodyAdvice implements RequestBodyAdvice {

	public MyRequestBodyAdvice() {
		System.out.println("MyRequestBodyAdvice");
	}

	@Override
	public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
		// 只支持MyData增强类型
		return methodParameter.getParameterType() == MyData.class;
	}

	@Override
	public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
		return null;
	}

	@Override
	public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
		return inputMessage;
	}

	@Override
	public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
		// 根据firstName和lastName设置fullName
		MyData myData = (MyData)body;
		myData.setFullName(myData.getFirstName() + myData.getLastName());
		return myData;
	}

}
